"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by siyi.chen on '21/11/2024'
    comment: cariabot自定义接口
"""
import json
from fastapi import APIRouter, BackgroundTasks, Body, Request, UploadFile, File

from config import Config
from project.core.function import json_response
from project.lib.decorator import api_common
from project.model.api_model import InterCariabot
from project.model.database.flow import Flow
from project.model.database.cariabot import CariabotView
from project.service.cariabot import CariabotService
from project.service.common.jpush import JpushService, CARIABOT_COLUMN_FLUSH
from project.service.common.mqtt import MQTTService


cariabot_router = APIRouter(prefix='/m', tags=['manager.cariabot'])


@cariabot_router.get('/cariabot/flow/list', summary='cariabot服务列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX), ), verify_login=True)
async def get_cariabot_flow_list(request: Request, session=None, operator=None):
    """
    **desc**: cariabot服务列表

    **url**: http(s)://{0}.udicaria.com.udicaria.com/m/cariabot/flow/list

    **method**: GET

    **params**: 无

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: [
                {
                    code: 服务流程编号
                    name: 服务流程名称
                }
            ]
        }
    """
    data = await Flow.fetch_all(session, wheres=(Flow.organization_code == operator.organization_code, ~Flow.is_deleted), orders=(Flow.id.desc()))
    items = [v.dict('code', 'name') for v in data]
    return json_response(data=items)


@cariabot_router.get('/cariabot/card/list', summary='cariabot卡片列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX), ), verify_login=True)
async def get_cariabot_card_list(request: Request, operator=None, session=None):
    """
    **desc**: cariabot卡片列表

    **url**: http(s)://{0}.udicaria.com.udicaria.com/m/cariabot/card/list

    **method**: GET

    **params**: 无

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: []
        }
    """
    ret_data = await CariabotService.get_cariabot_card_list(session, operator)
    return json_response(data=ret_data)


@cariabot_router.get('/cariabot/info', summary='获取cariabot自定义信息', response_model=CariabotView)
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX), ), verify_login=True)
async def get_cariabot_info(request: Request, session=None, operator=None):
    """
    **desc**: 获取cariabot自定义信息

    **url**: http(s)://{0}.udicaria.com.udicaria.com/m/cariabot/info

    **method**: GET

    **params**: 无

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: []
        }
    """
    ret_data = await CariabotService.get_cariabot_info(session, operator)
    return json_response(data=ret_data)


@cariabot_router.post('/cariabot/save', summary='保存cariabot自定义信息')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX), ), verify_login=True)
async def save_cariabot_info(request: Request,
                             background_tasks: BackgroundTasks,
                             inter_cariabot: InterCariabot = Body(..., title='Cariabot自定义信息'),
                             session=None,
                             operator=None):
    """
    **desc**: 保存cariabot自定义信息

    **url**: http(s)://{0}.udicaria.com.udicaria.com/m/cariabot/save

    **method**: POST

    **params**:

        <body>:
            background_image: 背景图
            digital_human_id: 数字人id
            digital_human_image: 数字人图片
            awaken: 唤醒词
            voice_icon: 语音图标
            columns: [
                {
                    id: 栏目id，新增时不传
                    name: 栏目名称
                    icon_checked: 图标选中状态
                    icon_unchecked: 图标未选中状态
                    column_type: 栏目类型 flow(服务流程)/card(服务卡片)/evaluation(健康评估)/sleep(睡眠方案)/human(呼叫前台)/home(返回首页)/external(外部模块)/agent(智能助理)/shortcut(快捷入口)/voip(语音通话)
                    service_list: [
                    {
                        code: 编号
                        name: 名称
                        image: 图片
                        url: 链接
                        premable: 开场白
                        rank: 排序
                    }] 服务流程列表
                    tags: [] 标签列表
                    preamble: 栏目开场白
                }
            ] 栏目列表

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: None
        }
    """
    ret_data = await CariabotService.save_cariabot_info(session, operator.organization_code, inter_cariabot)

    # 极光推送
    background_tasks.add_task(JpushService.push, session, organization_code=operator.organization_code, flow_code='', node_code='', _type=CARIABOT_COLUMN_FLUSH)
    # MQTT 推送
    background_tasks.add_task(MQTTService.push, topic=f'cariabot/{operator.organization_code}', message=json.dumps({'action': 'column_flush'}, ensure_ascii=False).encode('utf-8'))

    return json_response(data=ret_data)


@cariabot_router.post('/cariabot/column/delete', summary='删除cariabot栏目')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX), ), verify_login=True)
async def do_cariabot_column_delete(request: Request,
                                    background_tasks: BackgroundTasks,
                                    id: int = Body(..., title='栏目id', embed=True),
                                    session=None,
                                    operator=None):
    """
    **desc**: 删除cariabot栏目

    **url**: http(s)://{0}.udicaria.com.udicaria.com/m/cariabot/column/delete

    **method**: POST

    **params**:

        <body>:
            id: 栏目id

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: None
        }
    """
    ret_data = await CariabotService.do_cariabot_column_delete(session, operator.organization_code, id)

    return json_response(data=ret_data)

